import getopt,sys,cv2,os,time
import numpy as np

def do_mosaic(img, neighbor=9):
    h,w = img.shape[0], img.shape[1]
    for i in range(0, h , neighbor):
        for j in range(0, w , neighbor):
            rect = [j, i]
            color = img[i][j].tolist()
            left_up = (rect[0], rect[1])
            x=rect[0] + neighbor - 1
            y=rect[1] + neighbor - 1
            if x>w:
                x=w
            if y>h:
                y=h
            right_down = (x,y)
            cv2.rectangle(img, left_up, right_down, color, -1)
    return img

def do_resize(img, w, h):
    src_h, src_w = img.shape[0], img.shape[1]
    if(src_w / src_h >= w/h):
        resize_img = cv2.resize(img, (w, int(src_h * w / src_w)))
    else:
        resize_img = cv2.resize(img, (int(src_w * h / src_h), h))
    return resize_img

def do_show(img, label):
    cv2.imshow(label, img)
    cv2.waitKey(0)
    cv2.destroyWindow(label) 

def do_save(img, path):
    cv2.imwrite(os.path.join(path[0], "mos_{}_{}".format(time.time(), path[1])), img)

def do_trans2gray(img):
    return cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
try:
    neighbor = 9
    width = 0 
    height = 0
    path = ""
    needTrans = False
    opts,args = getopt.getopt(sys.argv[1:], "-n:-w:-h:-f:-g")
    for key,value in opts:
        if(key == "-n"):
            neighbor = int(value)
        elif(key == "-f"):
            img = cv2.imread(value)
            path = os.path.split(value)
        elif(key == "-w"):
            width = int(value)
        elif(key == "-h"):
            height = int(value)
        elif(key == "-g"):
            needTrans = True
    if(needTrans):
        img = do_trans2gray(img)
    if(width > 0 and height > 0):
        img = do_resize(img, width, height)
    img = do_mosaic(img, neighbor)
    do_show(img, "result")
    do_save(img, path)
except Exception as e:
    print(str(e))